<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="贷款机构" prop="bankCardLendId">
          <el-select v-model="queryParams.bankCardLendId" placeholder="请选择贷款机构" clearable>
            <el-option v-for="creditCard in creditCardList" :key="creditCard.id" :label="creditCard.nameCode" :value="creditCard.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="结清状态" prop="state">
          <el-select v-model="queryParams.state" placeholder="请选择账户状态" clearable>
            <el-option v-for="dict in settle_state" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['invest:installmentHistory:add']">新增</el-button>
          <!-- <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['invest:installmentHistory:remove']">删除</el-button> -->
          <!-- <el-button @click="handleExport" icon="Download" v-hasPermi="['invest:installmentHistory:export']">导出</el-button> -->
        </div>
      </div>
      <div class="content-con" v-loading="loading">
        <el-table v-loading="loading" :data="installmentHistoryList" @selection-change="handleSelectionChange" height="calc(100% - 0.62rem)">
          <el-table-column type="index" label="序号" :index="indexMethod" width="50"></el-table-column>
          <el-table-column label="贷款机构" align="center" width="150" prop="bankNameCode" />
          <el-table-column label="借款金额" align="center" prop="installmentAmount" />
          <el-table-column label="借款日期" align="center" prop="installmentDate" width="100">
            <template #default="scope">
              <span>{{ parseTime(scope.row.installmentDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="借款期数" align="center" width="80" prop="period" />
          <el-table-column label="已还期数" align="center" width="80" prop="repaidPeriod" />
          <el-table-column label="总利息" align="center" prop="totalInterest" />
          <el-table-column label="年化利率" align="center" width="80" prop="interestRate" />
          <el-table-column label="计算利率" align="center" width="80" prop="calculateInterestRate" />
          <el-table-column label="余额" align="center" prop="balance" />
          <el-table-column label="剩余本金" align="center" prop="outstandingPrincipal" />
          <el-table-column label="剩余利息" align="center" prop="outstandingInterest" />
          <el-table-column label="到期日期" align="center" prop="dueDate" width="100">
            <template #default="scope">
              <span>{{ parseTime(scope.row.dueDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最近还款日" align="center" prop="repaymentDate" width="100">
            <template #default="scope">
              <span>{{ parseTime(scope.row.repaymentDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="关闭日期" align="center" prop="closeDate" width="180">
                    <template #default="scope">
                      <span>{{ parseTime(scope.row.closeDate, '{y}-{m}-{d}') }}</span>
                    </template>
                  </el-table-column> -->
          <el-table-column label="结清状态" align="center" width="80" prop="state">
            <template #default="scope">
              <dict-tag :options="settle_state" :value="scope.row.state" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button :icon="item.icon" v-hasPermi="item.hasPermi" circle @click="handleOperate(item.id, scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加或修改贷款账单对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="installmentHistoryRef" :model="form" :inline="true" :rules="rules" label-width="120px">
        <el-form-item label="贷款机构" prop="bankCardLendId">
          <el-select v-model="form.bankCardLendId" placeholder="请选择贷款机构" clearable>
            <el-option v-for="creditCard in creditCardList" :key="creditCard.id" :label="creditCard.nameCode" :value="creditCard.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="借款日期" prop="installmentDate">
          <el-date-picker clearable v-model="form.installmentDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择借款日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="借款金额" prop="installmentAmount">
          <el-input v-model="form.installmentAmount" type="number" placeholder="请输入借款金额" />
        </el-form-item>
        <el-form-item label="总利息" prop="totalInterest">
          <el-input v-model="form.totalInterest" type="number" placeholder="请输入总利息" />
        </el-form-item>
        <el-form-item label="借款期数" prop="period">
          <el-input-number v-model="form.period" placeholder="借款期数" />
        </el-form-item>
        <el-form-item label="已还期数" prop="repaidPeriod">
          <el-input-number v-model="form.repaidPeriod" placeholder="已还期数" />
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="form.balance" type="number" placeholder="请输入余额" />
        </el-form-item>
        <el-form-item label="结清状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择账户状态">
            <el-option v-for="dict in settle_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="利率" prop="interestRate">
          <el-input v-model="form.interestRate" placeholder="请输入利率" />
        </el-form-item>

        <el-form-item label="关闭日期" prop="closeDate">
          <el-date-picker clearable v-model="form.closeDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择关闭日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" style="width: 792px" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看贷款账单'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改分期历史明细对话框 -->
    <el-dialog :title="titleDetail" v-model="openDetail" width="500px" append-to-body>
      <el-form ref="installmentDetailRef" :model="formDetail" :rules="rulesDetail" label-width="120px">
        <el-form-item label="还款日期" prop="repaymentDate">
          <el-date-picker clearable v-model="formDetail.repaymentDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择还款日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="还款期数" prop="periods">
          <el-input-number v-model="formDetail.periods" placeholder="还款期数" />
        </el-form-item>
        <el-form-item label="还款金额" prop="currentAmount">
          <el-input v-model="formDetail.currentAmount" type="number" placeholder="请输入还款金额" />
        </el-form-item>
        <el-form-item label="应还本金" prop="principal">
          <el-input v-model="formDetail.principal" type="number" placeholder="请输入应还本金" />
        </el-form-item>
        <el-form-item label="利息" prop="interest">
          <el-input v-model="formDetail.interest" type="number" placeholder="请输入利息" />
        </el-form-item>
        <el-form-item label="入账状态" prop="postingState">
          <el-select v-model="formDetail.postingState" placeholder="请选择入账状态">
            <el-option v-for="dict in posting_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formDetail.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDetail">确 定</el-button>
          <el-button @click="cancelDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改分期历史明细对话框 -->
    <el-dialog title="查看添加明细" v-model="detailOpen" width="1150px" append-to-body>
      <div class="basic-information">
        <div class="main-con">
          <div class="title-con">
            <div class="title">基本信息</div>
            <div class="operate-btn-con">
              <el-button @click="handleAddDetail" icon="Plus" v-hasPermi="['invest:installmentHistory:add']">新增</el-button>
              <el-button @click="handleUpdateInterest" icon="Expand" v-hasPermi="['invest:installmentHistory:add']">总利息汇总</el-button>
            </div>
          </div>
          <div class="content-con">
            <el-table v-loading="loading" :data="installmentDetailList">
              <el-table-column label="还款日期" align="center" prop="repaymentDate" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.repaymentDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="还款期数" align="center" prop="periods" />
              <el-table-column label="还款金额" align="center" prop="currentAmount" />

              <el-table-column label="应还本金" align="center" prop="principal" />
              <el-table-column label="利息" align="center" prop="interest" />
              <el-table-column label="入账状态" align="center" prop="postingState">
                <template #default="scope">
                  <dict-tag :options="posting_state" :value="scope.row.postingState" />
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template v-slot="scope">
                  <div class="ctrl-btn d-flex">
                    <el-tooltip v-for="item in operateDetailList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                      <el-button :icon="item.icon" v-hasPermi="item.hasPermi" circle @click="handleDetailOperate(item.id, scope.row)"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer> </template>
    </el-dialog>
  </div>
</template>

<script setup name="InstallmentHistory">
import {
  listInstallmentHistory,
  getInstallmentHistory,
  delInstallmentHistory,
  addInstallmentHistory,
  updateInstallmentHistory
} from '@/api/invest/installmentHistory'
import {
  listInstallmentDetail,
  getInstallmentDetail,
  delInstallmentDetail,
  addInstallmentDetail,
  updateInstallmentDetail
} from '@/api/invest/installmentDetail'
import { listBankcardLend } from '@/api/invest/bankcardlend'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
import dayjs from 'dayjs'
const { proxy } = getCurrentInstance()
const { settle_state, bank_card_type, posting_state } = proxy.useDict('settle_state', 'bank_card_type', 'posting_state')

const installmentHistoryList = ref([])
const installmentDetailList = ref([])
const open = ref(false)
const openDetail = ref(false)
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const titleDetail = ref('')
const currentInstallmentHistoryId = ref('')
const creditCardList = ref([])
const operateList = ref([
  { id: 'detail', icon: 'Grid', title: '查看添加明细', hasPermi: ['invest:installmentHistory:query'] },
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['invest:installmentHistory:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['invest:installmentHistory:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['invest:installmentHistory:remove'] }
])
const operateDetailList = ref([
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['invest:installmentHistory:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['invest:installmentHistory:remove'] }
])
const data = reactive({
  form: {},
  formDetail: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: '3',
    bankCardLendId: null,
    state: '0'
  },
  queryCreditCardParams: {
    pageNum: 1,
    type: '3',
    status: '1',
    lendType: '1',
    pageSize: 1000
  },
  rules: {
    bankCardLendId: [{ required: true, message: '贷款机构不能为空', trigger: 'blur' }],
    installmentAmount: [{ required: true, message: '借款金额不能为空', trigger: 'blur' }],
    installmentDate: [{ required: true, message: '借款日期不能为空', trigger: 'blur' }],
    period: [{ required: true, message: '借款期数不能为空', trigger: 'blur' }],
    repaidPeriod: [{ required: true, message: '已还期数不能为空', trigger: 'blur' }],
    totalInterest: [{ required: true, message: '总利息不能为空', trigger: 'blur' }],
    state: [{ required: true, message: '账户状态不能为空', trigger: 'change' }],
    balance: [{ required: true, message: '余额不能为空', trigger: 'blur' }]
  },
  rulesDetail: {
    installmentHistoryId: [{ required: true, message: '分期历史id不能为空', trigger: 'blur' }],
    bankCardLendId: [{ required: true, message: '信用卡贷款不能为空', trigger: 'blur' }],
    repaymentDate: [{ required: true, message: '还款日期不能为空', trigger: 'blur' }],
    principal: [{ required: true, message: '应还本金不能为空', trigger: 'blur' }],
    periods: [{ required: true, message: '还款期数不能为空', trigger: 'blur' }],
    interest: [{ required: true, message: '利息不能为空', trigger: 'blur' }],
    postingState: [{ required: true, message: '入账状态不能为空', trigger: 'change' }]
  }
})

const handleOperate = (operate, row) => {
  switch (operate) {
    case 'detail':
      handleDetail(row)
      break
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      break
  }
}

const handleDetailOperate = (operate, row) => {
  switch (operate) {
    case 'edit':
      handleUpdateDetail(row)
      break
    case 'delete':
      handleDeleteDetail(row)
      break
    default:
      break
  }
}

const { queryParams, queryCreditCardParams, form, rules, formDetail, rulesDetail } = toRefs(data)

/** 查询贷款机构卡管理列表 */
function getCreditCardList() {
  listBankcardLend(queryCreditCardParams.value).then((response) => {
    creditCardList.value = response.rows
  })
}

/** 查询贷款账单列表 */
function getList() {
  loading.value = true
  listInstallmentHistory(queryParams.value).then((response) => {
    installmentHistoryList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 取消按钮
function cancelDetail() {
  openDetail.value = false
  resetDetail()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    type: '3',
    code: null,
    balance: null,
    bankCardLendId: null,
    installmentAmount: null,
    installmentDate: null,
    period: null,
    repaidPeriod: null,
    totalInterest: null,
    interestRate: null,
    dueDate: null,
    closeDate: null,
    state: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null
  }
  proxy.resetForm('installmentHistoryRef')
}

// 表单重置
function resetDetail() {
  formDetail.value = {
    id: null,
    installmentHistoryId: null,
    bankCardLendId: null,
    currentAmount: null,
    repaymentDate: null,
    principal: null,
    interest: null,
    postingState: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    type: '3',
    periods: null
  }
  proxy.resetForm('installmentDetailRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.value.state = null
  handleQuery()
}

// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

//每页显示条数改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}
// 序号翻页递增
const indexMethod = (index) => {
  const nowPage = queryParams.value.pageNum //当前第几页，根据组件取值即可
  const nowLimit = queryParams.value.pageSize //当前每页显示几条，根据组件取值即可
  return index + 1 + (nowPage - 1) * nowLimit // 这里可以理解成一个公式
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看
const handleView = (row) => {
  title.value = '查看贷款账单'
  form.value = row
  open.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  form.value.installmentDate = dayjs(new Date().getTime()).format('YYYY-MM-DD')
  open.value = true
  title.value = '添加贷款账单'
}

/** 新增按钮操作 */
function handleAddDetail() {
  resetDetail()
  formDetail.value.repaymentDate = dayjs(new Date().getTime()).format('YYYY-MM-DD')
  titleDetail.value = '添加贷款明细'
  openDetail.value = true
}

/** 总利息按钮操作 */
function handleUpdateInterest() {
  let totalInterest = 0
  for (let i = 0; i < installmentDetailList.value.length; i++) {
    if (installmentDetailList.value[i].interest) {
      totalInterest = totalInterest + installmentDetailList.value[i].interest
    }
  }
  getInstallmentHistory(currentInstallmentHistoryId.value).then((response) => {
    form.value = response.data
    form.value.totalInterest = totalInterest
    if (form.value.id != null) {
      updateInstallmentHistory(form.value).then((response) => {
        proxy.$modal.msgSuccess('总利息汇总成功！')
        openDetail.value = false
        getList()
      })
    }
  })
}
/** 新增按钮操作 */
function handleDetail(row) {
  detailOpen.value = true
  formDetail.value.installmentHistoryId = row.id
  currentInstallmentHistoryId.value = row.id
  formDetail.value.bankCardLendId = row.bankCardLendId
  formDetail.value.type = row.type
  listInstallmentDetail({ installmentHistoryId: row.id, pageNum: 1, pageSize: 1000 }).then((response) => {
    installmentDetailList.value = response.rows
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getInstallmentHistory(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改贷款账单'
  })
}

/** 修改按钮操作 */
function handleUpdateDetail(row) {
  resetDetail()
  getInstallmentDetail(row.id).then((response) => {
    formDetail.value = response.data
    openDetail.value = true
    titleDetail.value = '修改贷款明细'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.installmentHistoryRef.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateInstallmentHistory(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addInstallmentHistory(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 提交按钮 */
function submitFormDetail() {
  proxy.$refs.installmentDetailRef.validate((valid) => {
    if (valid) {
      if (formDetail.value.id != null) {
        updateInstallmentDetail(formDetail.value).then((response) => {
          proxy.$modal.msgSuccess('修改明细成功')
          openDetail.value = false
          listInstallmentDetail({ installmentHistoryId: currentInstallmentHistoryId.value, pageNum: 1, pageSize: 1000 }).then((response) => {
            installmentDetailList.value = response.rows
          })
        })
      } else {
        addInstallmentDetail(formDetail.value).then((response) => {
          proxy.$modal.msgSuccess('新增明细成功')
          openDetail.value = false
          listInstallmentDetail({ installmentHistoryId: currentInstallmentHistoryId.value, pageNum: 1, pageSize: 1000 }).then((response) => {
            installmentDetailList.value = response.rows
          })
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delInstallmentHistory(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 删除按钮操作 */
function handleDeleteDetail(row) {
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delInstallmentDetail(row.id)
    })
    .then(() => {
      listInstallmentDetail({ installmentHistoryId: currentInstallmentHistoryId.value, pageNum: 1, pageSize: 1000 }).then((response) => {
        installmentDetailList.value = response.rows
      })
      proxy.$modal.msgSuccess('删除分期历史明细成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'invest/installmentHistory/export',
    {
      ...queryParams.value
    },
    `installmentHistory_${new Date().getTime()}.xlsx`
  )
}

getCreditCardList()
getList()
</script>
